package com.yanqu.road.server.gameplayer.module.activity.goldautumn;

import com.yanqu.road.dao.impl.activity.goldautumn.GoldAutumnUserDataDaoImpl;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.args.ValueParamArgs;
import com.yanqu.road.entity.activity.goldautumn.GoldAutumnBuff;
import com.yanqu.road.entity.activity.goldautumn.GoldAutumnCell;
import com.yanqu.road.entity.activity.goldautumn.GoldAutumnConfig;
import com.yanqu.road.entity.activity.goldautumn.GoldAutumnUserData;
import com.yanqu.road.entity.activity.goldautumn.config.GoldAutumnBuffInfo;
import com.yanqu.road.entity.activity.goldautumn.config.GoldAutumnLatticeInfo;
import com.yanqu.road.entity.activity.goldautumn.config.GoldAutumnLevelInfo;
import com.yanqu.road.entity.activity.goldautumn.config.GoldAutumnScreedInfo;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.enums.eSystemId;
import com.yanqu.road.entity.log.LogGoldAutumnMove;
import com.yanqu.road.entity.player.UserBagItem;
import com.yanqu.road.pb.activity.GoldAutumnProto;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.player.BagModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.manger.ServerLanguageMgr;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.goldautumn.GoldAutumnMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.manger.log.AutoLogMgr;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.mina.util.ConcurrentHashSet;

import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class GoldAutumnModule extends GeneralModule {

    GoldAutumnUserData userData;

    public GoldAutumnModule(GamePlayer player) {
        super(player);
    }

    @Override
    public boolean loadData() {
        ActivityInfo activityInfo = GoldAutumnMgr.getActivityInfo();
        if(ActivityMgr.activityInShowTime(activityInfo)) {
            userData = new GoldAutumnUserDataDaoImpl().getGoldAutumnUserData(activityInfo.getActivityId(), player.getUserId());
        }
        return true;
    }

    @Override
    public boolean afterLoadData() {
        return true;
    }

    @Override
    public boolean saveData() {

        if(userData != null){
            if(userData.isInsertOption()){
                new GoldAutumnUserDataDaoImpl().add(userData);
            }else if(userData.isUpdateOption()){
                new GoldAutumnUserDataDaoImpl().update(userData);
            }
        }

        return true;
    }

    @Override
    public void afterLogin() {
        activityReload();
    }

    public void activityReload() {

        if (!SystemOpenMgr.systemOpen(player, eSystemId.GoldAutumnActivity.getValue())) {
            return;
        }

        GoldAutumnConfig config = GoldAutumnMgr.getConfig();
        if(config == null || !ActivityMgr.activityInShowTime(config.getActivityInfo())){
            return;
        }

        syncConfig(config);

        initUserData(config);

        if(!resetOneDay()) {
            syncUserData(config);
        }

        //moveForTest();
    }

    private void syncConfig(GoldAutumnConfig config) {
        GoldAutumnProto.GoldAutumnActivityConfigSync.Builder builder = GoldAutumnProto.GoldAutumnActivityConfigSync.newBuilder();
        for (GoldAutumnBuffInfo buffInfo : config.getBuffInfoList()) {
            GoldAutumnProto.GoldAutumnBuffInfoTemp.Builder buffBuilder = GoldAutumnProto.GoldAutumnBuffInfoTemp.newBuilder();
            buffBuilder.setId(buffInfo.getId());
            buffBuilder.setParam(String.valueOf(buffInfo.getParam()));
            buffBuilder.setName(ServerLanguageMgr.getContent(buffInfo.getName(), player.getLanguage()));
            buffBuilder.setDesc(ServerLanguageMgr.getContent(buffInfo.getDesc(), player.getLanguage()));
            builder.addBuff(buffBuilder);
        }
        for (GoldAutumnLevelInfo levelInfo : config.getLevelInfoList()) {
            GoldAutumnProto.GoldAutumnLevelInfoTemp.Builder levelInfoBuild = GoldAutumnProto.GoldAutumnLevelInfoTemp.newBuilder();
            levelInfoBuild.setId(levelInfo.getId());
            levelInfoBuild.setUnlock(levelInfo.getUnlock());
            levelInfoBuild.setCostNumber(levelInfo.getCostNumber());
            levelInfoBuild.setGetMagnification(levelInfo.getGetMagnification());
            builder.addLevel(levelInfoBuild);
        }
        for (GoldAutumnLatticeInfo latticeInfo : config.getLatticeInfoList()) {
            GoldAutumnProto.GoldAutumnLatticeTemp.Builder latticeBuild = GoldAutumnProto.GoldAutumnLatticeTemp.newBuilder();
            latticeBuild.setId(latticeInfo.getId());
            latticeBuild.setColorType(latticeInfo.getColorType());
            latticeBuild.setType(latticeInfo.getType());
            latticeBuild.setWeight(latticeInfo.getWeight());
            latticeBuild.setSquareType(latticeInfo.getSquareType());
            latticeBuild.setReward(latticeInfo.getReward());
            builder.addLattice(latticeBuild);
        }
        player.sendPacket(Protocol.U_GOLD_AUTUMN_SYNC_CONFIG, builder);
    }

    private synchronized void initUserData(GoldAutumnConfig config) {

        if(userData == null || userData.getActivityId() != config.getActivityInfo().getActivityId()){

            userData = createUserData(config, player.getUserId());

        }
    }

    private GoldAutumnUserData createUserData(GoldAutumnConfig config, long userId) {
        GoldAutumnUserData tempData = new GoldAutumnUserData();
        tempData.setUserId(userId);
        tempData.setActivityId(config.getActivityInfo().getActivityId());

        tempData.setStepSet(new ConcurrentHashSet<>());
        tempData.setBuffMap(new ConcurrentHashMap<>());
        tempData.setCellList(new ArrayList<>());
        tempData.setLastCellList(new ArrayList<>());

        initUserStep(tempData);

        List<GoldAutumnCell> cellList = GoldAutumnMgr.initNextCell(tempData.getLastCellList(), tempData.getCurCellId(), tempData.getMaxCellId(), config);
        tempData.setMaxCellId(tempData.getMaxCellId() + cellList.size());
        tempData.addCellList(cellList);

        //初始生最后格子，缓存起来
        List<GoldAutumnCell> lastCellList = new ArrayList<>();
        int start = config.getRedCellIdList().get(config.getRedCellIdList().size() - 1) - 10;
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            GoldAutumnScreedInfo screedInfo = config.randomGoldAutumnScreedInfo(start, random);
            List<Integer> addList = GoldAutumnMgr.getRandomColor(random, screedInfo);
            if (addList == null){
                continue;
            }
            lastCellList.addAll(GoldAutumnMgr.initCellParam(start, addList, config));
            start += addList.size();
        }
        tempData.setLastCellList(lastCellList);

        checkCellLength(tempData);
        tempData.setInsertOption();
        return tempData;
    }

    public void checkCellLength(GoldAutumnUserData userData){
        //保留前面30格
        int num = 30;
        boolean change = false;
        while (userData.getCellList().size() > 0 && userData.getCellList().get(0).getId() + num < userData.getCurCellId()){
            userData.getCellList().remove(0);
            change = true;
        }
        if(change){
            userData.setUpdateOption();
        }
    }

    private Set<Integer> initUserStep(GoldAutumnUserData userData) {
        if(userData.getStepSet().size() > 0){
            return userData.getStepSet();
        }
        Set<Integer> stepSet = generalStepSet();
        userData.setStepSet(stepSet);
        return stepSet;
    }

    private Set<Integer> generalStepSet() {
        Set<Integer> stepSet = new HashSet<>();
        for (int i = 1; i <= 4; i++) {
            stepSet.add(i);
        }
        return stepSet;
    }

    public boolean resetOneDay(){

        if(userData == null){
            return false;
        }

        // 没有活动
        if (!ActivityMgr.activityInTime(GoldAutumnMgr.getActivityInfo()) || GoldAutumnMgr.getConfig() == null) {
            return false;
        }

        GoldAutumnConfig config = GoldAutumnMgr.getConfig();
//        int zeroTime = DateHelper.getTodayZeroTime();
//        if(userData.getResetTime() != zeroTime){
//            userData.setResetTime(zeroTime);
//            syncUserData(config);
//            return true;
//        }
        return false;
    }

    private void syncUserData(GoldAutumnConfig config) {
        if(userData != null){
            GoldAutumnProto.GoldAutumnUserDataSync.Builder dataSync = GoldAutumnProto.GoldAutumnUserDataSync.newBuilder();
            dataSync.setUserData(buildUserData());
            player.sendPacket(Protocol.U_GOLD_AUTUMN_SYNC_USER_DATA, dataSync);
        }
    }

    private GoldAutumnProto.GoldAutumnUserDataTemp.Builder buildUserData() {
        GoldAutumnProto.GoldAutumnUserDataTemp.Builder userBuild = GoldAutumnProto.GoldAutumnUserDataTemp.newBuilder();
        userBuild.setScore(userData.getScore());
        userBuild.addAllStep(userData.getStepSet());
        userBuild.setTotalCost(userData.getTotalCost());
        userBuild.setCurCellId(userData.getCurCellId());
        for (GoldAutumnCell autumnCell : userData.getCellList()) {
            GoldAutumnProto.GoldAutumnCellTemp.Builder cellBuild = GoldAutumnProto.GoldAutumnCellTemp.newBuilder();
            cellBuild.setId(autumnCell.getId());
            cellBuild.setConfigId(autumnCell.getCid());
            cellBuild.setGet(autumnCell.getGet() == 1);
            cellBuild.setEvent(autumnCell.getEid());
            cellBuild.setReward(autumnCell.getR());
            userBuild.addCell(cellBuild);
        }

        for (GoldAutumnCell autumnCell : userData.getLastCellList()) {
            GoldAutumnProto.GoldAutumnCellTemp.Builder cellBuild = GoldAutumnProto.GoldAutumnCellTemp.newBuilder();
            cellBuild.setId(autumnCell.getId());
            cellBuild.setConfigId(autumnCell.getCid());
            cellBuild.setGet(autumnCell.getGet() == 1);
            cellBuild.setEvent(autumnCell.getEid());
            cellBuild.setReward(autumnCell.getR());
            userBuild.addLastCell(cellBuild);
        }

        for (Map.Entry<Integer, GoldAutumnBuff> buffEntry : userData.getBuffMap().entrySet()) {
            GoldAutumnBuff buff = buffEntry.getValue();
            GoldAutumnProto.GoldAutumnBuffTemp.Builder builder = GoldAutumnProto.GoldAutumnBuffTemp.newBuilder();
            builder.setId(buff.getId());
            builder.setTimes(buff.getTimes());
            userBuild.addBuff(builder);
        }
        return userBuild;
    }

    public int getUserData() {
        if(userData == null){
            return GameErrorCode.E_SYSTEM_NO_OPEN;
        }
        GoldAutumnProto.GoldAutumnEnterGameRespMsg.Builder syncBuilder = GoldAutumnProto.GoldAutumnEnterGameRespMsg.newBuilder();
        syncBuilder.setRet(0);
        syncBuilder.setUserData(buildUserData());
        player.sendPacket(Protocol.U_GOLD_AUTUMN_GET_USER_DATA, syncBuilder);
        return 0;
    }

    /**
     * @param step 等于0代表自动，大于0是具体步数
     */
    public int move(int step) {
        if(userData == null){
            return GameErrorCode.E_SYSTEM_NO_OPEN;
        }
        GoldAutumnConfig config = GoldAutumnMgr.getConfig();
        if(config == null){
            return GameErrorCode.E_ACTIVITY_OVER_TIME;
        }

        //待规划的池子
        List<Integer> poolList = new ArrayList<>();
        if(step == 0){
            //积分是否达到条件
            if(userData.getCurCellId() < config.getAUTUMN_AUTO_OPEN()){
                return GameErrorCode.E_GOLD_AUTUMN_AUTO_MODE_LIMIT;
            }
            poolList.addAll(userData.getStepSet());
        }else {
            if(!userData.getStepSet().contains(step)){
                return GameErrorCode.E_REQUEST_ARGUMENT_ERROR;
            }
            poolList.add(step);
        }

        if(poolList.size() == 0){
            return GameErrorCode.E_ERROR_DATA;
        }

        int costItemId = config.getENERGY_ITEM_ID();
        UserBagItem bagItem = player.getModule(BagModule.class).getUserBagItem(costItemId);
        if(bagItem == null || bagItem.getNum() <= 0){
            GoldAutumnBuff buff = userData.getBuffMap().get(3);
            if(buff == null || buff.getTimes() <= 0) {
                return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
            }
        }

        //先规划，规划与消耗无关
        List<Integer> selectList = new ArrayList<>();
        if(step > 0){
            //单次
            selectList.add(step);
            //其他剩余
            for (int other : userData.getStepSet()) {
                if(other != step){
                    selectList.add(other);
                }
            }
        }else {
            //多次，穷尽
            GoldAutumnJumpPlanResult jumpResult = GoldAutumnMgr.getBestJump(userData, userData.getCurCellId(), poolList);
            if(jumpResult != null){
                selectList.addAll(jumpResult.getStepList());
                //GoldAutumnMgr.getLogger().info("当前格子：{}，规划结果：{}", userData.getCurCellId(), selectList);
            }
        }

        if(selectList.size() == 0){
            return GameErrorCode.E_ERROR_DATA;
        }

        //消耗道具获得的积分
        Property scoreProperty = new Property();
        //历史累计（弃用）
        int tempTotalCost = userData.getTotalCost();
        //本次需要消耗
        int allNeedCost = 0;
        GoldAutumnJumpContext context = new GoldAutumnJumpContext(selectList);
        //是否自动模式
        context.setAuto(step == 0);
        if (context.getBeginStepList().size() > 0){
            int cost = 0;
            //消耗递增
            //免费的buff
            GoldAutumnBuff buff = userData.getBuffMap().get(3);
            int curCellId = userData.getCurCellId();
            GoldAutumnLevelInfo levelInfo = GoldAutumnMgr.getByCostNum(curCellId, config);
            if(buff == null || buff.getTimes() <= 0){
                cost = levelInfo.getCostNumber();
                allNeedCost += cost;
                tempTotalCost += cost;
                if (bagItem == null || bagItem.getNum() < allNeedCost) {
                    return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
                }
            }else {
                //免费buff扣次数
                buff.setTimes(buff.getTimes() - 1);
            }
            int nextStep = context.getBeginStepList().remove(0);
            GoldAutumnJumpStep jumpStep = new GoldAutumnJumpStep(nextStep);
            jumpStep.setCost(cost);
            jumpStep.getShowDta().setUseStep(nextStep);
            jumpCell(context, jumpStep, userData, config, false);
            //积分
            if(cost > 0){
                Property property = calScoreByCost(config, cost, levelInfo);
                scoreProperty.addProperty(property);
            }
        }

        //剩余格子
        userData.setStepSet(new HashSet<>(context.getBeginStepList()));

        player.getModule(CurrencyModule.class).removeCurrency(PropertyHelper.parseStringToProperty(config.getENERGY_ITEM_ID() + "=" + allNeedCost), eLogMoneyType.GoldAutumnActivity, eLogMoneyType.GoldAutumnActivityJumpConsume);

        Property allReward = new Property();
        allReward.addProperty(context.getRedReward());
        allReward.addProperty(scoreProperty);
        for (GoldAutumnJumpStep jumpStep : context.getAllStepList()) {
            allReward.addProperty(jumpStep.getProperty());
        }

        userData.setTotalCost(tempTotalCost);
        userData.setScore(userData.getScore() + allReward.getCountByGoodsId(config.getSCORE_ITEM_ID()).longValue());

        player.getModule(CurrencyModule.class).addCurrency(allReward, eLogMoneyType.GoldAutumnActivity, eLogMoneyType.GoldAutumnActivityJumpReward);

        //GoldAutumnMgr.getLogger().info("剩余步数：{}", userData.getStepSet());
        initUserStep(userData);
        //保证格子足够
        List<GoldAutumnCell> cellList = GoldAutumnMgr.initNextCell(userData.getLastCellList(), userData.getCurCellId(), userData.getMaxCellId(), config);
        if(cellList.size() > 0) {
            userData.getCellList().addAll(cellList);
            userData.setMaxCellId(userData.getMaxCellId() + cellList.size());
        }
        //GoldAutumnMgr.getLogger().info("剩余步数：{}", userData.getStepSet());

        player.notifyListener(eGamePlayerEventType.GoldAutumnScoreCrossRank.getValue(), new ValueParamArgs(userData.getScore(), ""));
        //处理跳格及前端动画
        GoldAutumnProto.GoldAutumnMoveRespMsg.Builder respMsg = GoldAutumnProto.GoldAutumnMoveRespMsg.newBuilder();
        for (GoldAutumnJumpStep jumpStep : context.getAllStepList()) {
            if(jumpStep.getShowDta() != null) {
                respMsg.addShowData(jumpStep.getShowDta());
            }
        }
        respMsg.setGoodsToScore(scoreProperty.getCountByGoodsId(config.getSCORE_ITEM_ID()).intValue());
        respMsg.setRet(0);
        respMsg.setUserData(buildUserData());
        player.sendPacket(Protocol.U_GOLD_AUTUMN_MOVE, respMsg);

        checkCellLength(userData);
        return 0;
    }

    /**
     * 跑数据
     */
    public void moveForTest(){

        Logger logger = LogManager.getLogger("DATASOURCE_STAT");

        GoldAutumnConfig config = GoldAutumnMgr.getConfig();
        if(config == null){
            return;
        }

        //1千个玩家
        for (int i = 0; i < 1000; i++) {
            //限制总消耗
            int totalCost = 60;
            GoldAutumnUserData userData = createUserData(config, i);
            //结果
            List<GoldAutumnJumpContext> contextList = new ArrayList<>();
            int realCost = 0;

            while (totalCost > 0){

                //免费的buff
                GoldAutumnBuff buff = userData.getBuffMap().get(3);

                //消耗
                int cost = 0;
                GoldAutumnLevelInfo levelInfo = GoldAutumnMgr.getByCostNum(userData.getCurCellId(), config);
                if(buff == null || buff.getTimes() <= 0) {
                    //沒有buff，扣除消耗
                    totalCost = totalCost - levelInfo.getCostNumber();
                    cost = levelInfo.getCostNumber();
                }else {
                    buff.setTimes(buff.getTimes() - 1);
                }
                if(totalCost >= 0){
                    realCost += cost;
                    //确认格子足够
                    GoldAutumnMgr.initNextCell(userData.getLastCellList(), userData.getCurCellId(), userData.getMaxCellId(), config);
                    initUserStep(userData);

                    List<Integer> poolList = new ArrayList<>(userData.getStepSet());
                    //规划
                    GoldAutumnJumpPlanResult jumpResult = GoldAutumnMgr.getBestJump(userData, userData.getCurCellId(), poolList);

                    GoldAutumnJumpContext context = new GoldAutumnJumpContext(jumpResult.getStepList());
                    //是否自动模式
                    context.setAuto(true);
                    int nextStep = context.getBeginStepList().remove(0);
                    GoldAutumnJumpStep jumpStep = new GoldAutumnJumpStep(nextStep);
                    jumpStep.setCost(cost);
                    jumpStep.getShowDta().setUseStep(nextStep);
                    jumpCell(context, jumpStep, userData, config, true);

                    //剩余格子
                    userData.setStepSet(new HashSet<>(context.getBeginStepList()));

                    contextList.add(context);

                    //消耗道具获得的积分
                    Property scoreProperty = new Property();
                    if(cost > 0){
                        Property property = calScoreByCost(config, cost, levelInfo);
                        scoreProperty.addProperty(property);
                    }

                    Property allReward = new Property();
                    allReward.addProperty(context.getRedReward());
                    allReward.addProperty(scoreProperty);
                    for (GoldAutumnJumpStep temp : context.getAllStepList()) {
                        allReward.addProperty(temp.getProperty());
                    }
                    userData.setTotalCost(realCost);
                    userData.setScore(userData.getScore() + allReward.getCountByGoodsId(config.getSCORE_ITEM_ID()).longValue());
                }
            }

            //输出当前玩家的数据
            logger.info("====第{}次，消耗{},格子数{},月桂币{}", i + 1, realCost, userData.getCurCellId(), userData.getScore());
            //统计跳中的颜色
            //阶段，颜色，个数
            Map<Integer, Map<Integer, Integer>> stageColorCountMap = new HashMap<>();
            for (GoldAutumnJumpContext context : contextList) {
                for (GoldAutumnJumpStep jumpStep : context.getAllStepList()) {
                    if(jumpStep.getCell().getCid() > 0){
                        GoldAutumnLatticeInfo latticeInfo = config.getGoldAutumnLatticeInfo(jumpStep.getCell().getCid());
                        if(latticeInfo != null){
                            if(!stageColorCountMap.containsKey(latticeInfo.getStage())){
                                stageColorCountMap.put(latticeInfo.getStage(), new HashMap<>());
                            }
                            int old = stageColorCountMap.get(latticeInfo.getStage()).getOrDefault(jumpStep.getCell().getCt(), 0);
                            stageColorCountMap.get(latticeInfo.getStage()).put(jumpStep.getCell().getCt(), old + 1);
                        }
                    }
                }
            }
            for (int stage = 1; stage <= stageColorCountMap.size(); stage++) {
                if(stageColorCountMap.containsKey(stage)){
                    Map<Integer, Integer> map = stageColorCountMap.get(stage);
                    if(map != null){
                        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
                            logger.info("====第{}次，阶段{},颜色{}，数量 {}", i + 1, stage, entry.getKey(), entry.getValue());
                        }
                    }
                }
            }
        }

    }

    private Property calScoreByCost(GoldAutumnConfig config, int cost, GoldAutumnLevelInfo levelInfo) {
        Property property = PropertyHelper.parseStringToProperty(config.getSCORE_ITEM_ID() + "=" + config.getSCORE_ITEM_NUMBER());
        property.rideProperty(cost);
        return property;
    }


    /**
     * 跳格子
     * @param context
     * @param step 步数
     * @param testMode 测试模式
     */
    public void jumpCell(GoldAutumnJumpContext context, GoldAutumnJumpStep step, GoldAutumnUserData userData, GoldAutumnConfig config, boolean testMode){
        //计算当前步数
        step.setCellId(step.getStep() + userData.getCurCellId());
        //更新步数
        userData.setCurCellId(step.getCellId());
        step.getShowDta().setBlockId(step.getCellId());

        //保证格子足够
        List<GoldAutumnCell> cellList = GoldAutumnMgr.initNextCell(userData.getLastCellList(), step.getCellId(), userData.getMaxCellId(), config);
        if(cellList.size() > 0) {
            userData.getCellList().addAll(cellList);
            userData.setMaxCellId(userData.getMaxCellId() + cellList.size());
            //GoldAutumnMgr.getLogger().info("当前跳格子：{}, 最大格子 {}", step.getCellId(), userData.getMaxCellId());
        }

        //倍数
        GoldAutumnLevelInfo levelInfo = GoldAutumnMgr.getByCostNum(userData.getCurCellId(), config);

        GoldAutumnCell cell = GoldAutumnMgr.getGoldAutumnCellById(userData, step.getCellId());

        //GoldAutumnMgr.getLogger().info("当前跳格子：{}, 使用步数 {}， 剩余步数 {}", step.getCellId(), step.getStep(), context.getBeginStepList());

        if(cell.getGet() == 1){
            //容错
            return;
        }

        int logScoreItem = 0;
        if(step.getCost() > 0){
            Property property = calScoreByCost(config, step.getCost(), levelInfo);
            logScoreItem += property.getCountByGoodsId(config.getSCORE_ITEM_ID()).intValue();
        }

        cell.setGet(1);
        step.setCell(cell);
        context.getAllStepList().add(step);

        if(cell.getCid() == 0 && cell.getCt() == 5){
            //红色大奖，不翻倍
            Property property = PropertyHelper.parseStringToProperty(cell.getR());
            step.setProperty(property);
            step.getShowDta().setReward(cell.getR());
            //GoldAutumnMgr.getLogger().info("当前跳格子：{} 是大奖", step.getCellId());

            //日志
            if (!testMode){
                AutoLogMgr.add(new LogGoldAutumnMove(userData.getUserId(), userData.getActivityId(), context.isAuto() ? 1 : 0,
                        step.getCost(), userData.getCurCellId(), step.getStep(), cell.getCt(), 0, 0, 0, logScoreItem, cell.getR()));
            }
            return;
        }

        //是否经过红色大奖
        List<GoldAutumnCell>  passList = GoldAutumnMgr.getGoldAutumnCellById(userData, userData.getCurCellId() - step.getStep() + 1, step.getStep());
        for (GoldAutumnCell autumnCell : passList) {
            if(autumnCell.getGet() == 1){
                continue;
            }
            if(autumnCell.getCid() == 0 && autumnCell.getCt() == 5){
                //红色大奖，不翻倍
                Property property = PropertyHelper.parseStringToProperty(autumnCell.getR());
                context.getRedReward().addProperty(property);
                autumnCell.setGet(1);
                step.setGetRed(true);
                //GoldAutumnMgr.getLogger().info("当前跳格子：{} 经过大奖格子{}", step.getCellId(), autumnCell.getId());
            }
        }

        GoldAutumnLatticeInfo latticeInfo = config.getGoldAutumnLatticeInfo(cell.getCid());

        if (latticeInfo.getType() == 1) {
            //月桂币(不翻倍)
            Property property = PropertyHelper.parseStringToProperty(latticeInfo.getReward());
            step.setProperty(property);
            step.getShowDta().setReward(PropertyHelper.parsePropertyToString(property));
            //GoldAutumnMgr.getLogger().info("当前跳格子：{}，获得月桂币 {}", step.getCellId(), step.getShowDta().getReward());

            logScoreItem += property.getCountByGoodsId(config.getSCORE_ITEM_ID()).intValue();

            //日志
            if (!testMode){
                AutoLogMgr.add(new LogGoldAutumnMove(userData.getUserId(), userData.getActivityId(), context.isAuto() ? 1 : 0,
                        step.getCost(), userData.getCurCellId(), step.getStep(), cell.getCt(), latticeInfo.getType(), latticeInfo.getId(), 0, logScoreItem, ""));
            }

        } else if (latticeInfo.getType() == 3) {
            //随机一个buff来玩
            GoldAutumnBuffInfo buffInfo = config.randomGoldAutumnBuffInfo(new Random());
            if (buffInfo.getId() == 2) {
                //岁捻年丰（不翻倍）
                List<Integer> numList = StringUtils.stringToIntegerList(buffInfo.getParam(), "\\|");
                Property property = PropertyHelper.parseStringToProperty(config.getSCORE_ITEM_ID() + "=" + numList.get(levelInfo.getId() - 1));
                step.setProperty(property);
                step.getShowDta().setReward(PropertyHelper.parsePropertyToString(property));
                step.setBuff(new GoldAutumnBuff(2));

                logScoreItem += property.getCountByGoodsId(config.getSCORE_ITEM_ID()).intValue();

                step.getShowDta().setBuff(GoldAutumnProto.GoldAutumnBuffTemp.newBuilder().setId(2).setTimes(1));
                //GoldAutumnMgr.getLogger().info("当前跳格子：{}，buff 获得月桂币 {}", step.getCellId(), PropertyHelper.parsePropertyToString(property));

                //日志
                AutoLogMgr.add(new LogGoldAutumnMove(userData.getUserId(), userData.getActivityId(), context.isAuto() ? 1 : 0,
                        step.getCost(), userData.getCurCellId(), step.getStep(), cell.getCt(), latticeInfo.getType(), latticeInfo.getId(), buffInfo.getId(), logScoreItem, PropertyHelper.parsePropertyToString(property)));

            } else if (buffInfo.getId() == 3) {
                //悠然自得
                int times = Integer.parseInt(buffInfo.getParam());
                GoldAutumnBuff buff = userData.getBuffMap().getOrDefault(3, new GoldAutumnBuff(3));
                buff.setTimes(buff.getTimes() + times);
                userData.getBuffMap().put(3, buff);
                userData.setUpdateOption();
                GoldAutumnBuff tempBuff = new GoldAutumnBuff(3);
                tempBuff.setTimes(times);
                step.setBuff(tempBuff);
                //GoldAutumnMgr.getLogger().info("当前跳格子：{}, buff  悠然自得 次数{}", step.getCellId(), buffInfo.getParam());

                step.getShowDta().setBuff(GoldAutumnProto.GoldAutumnBuffTemp.newBuilder().setId(3).setTimes(times));

                //日志
                if (!testMode){
                    AutoLogMgr.add(new LogGoldAutumnMove(userData.getUserId(), userData.getActivityId(), context.isAuto() ? 1 : 0,
                            step.getCost(), userData.getCurCellId(), step.getStep(), cell.getCt(), latticeInfo.getType(), latticeInfo.getId(), buffInfo.getId(), logScoreItem, ""));
                }

            } else if (buffInfo.getId() == 4) {
                if(step.getSrcBuffId() == 4){
                    //GoldAutumnMgr.getLogger().info("当前跳格子：{}, buff 福祸相依, 被忽略", step.getCellId());
                    return;
                }
                //GoldAutumnMgr.getLogger().info("当前跳格子：{}, buff 福祸相依触发", step.getCellId());
                //福祸相依
                step.setBuff(new GoldAutumnBuff(4));
                List<Integer> list;
                if(context.getBeginStepList().size() > 0){
                    list = new ArrayList<>(context.getBeginStepList());
                    context.getBeginStepList().clear();
                }else {
                    //初始下一次4个月珠
                    list = new ArrayList<>(generalStepSet());
                }
                step.getShowDta().setBuff(GoldAutumnProto.GoldAutumnBuffTemp.newBuilder().setId(4).setTimes(1));

                //日志
                if (!testMode){
                    AutoLogMgr.add(new LogGoldAutumnMove(userData.getUserId(), userData.getActivityId(), context.isAuto() ? 1 : 0,
                            step.getCost(), userData.getCurCellId(), step.getStep(), cell.getCt(), latticeInfo.getType(), latticeInfo.getId(), buffInfo.getId(), logScoreItem, ""));
                }

                //规划
                GoldAutumnJumpPlanResult planResult = GoldAutumnMgr.getBestJump(userData, userData.getCurCellId(), list);
                if(planResult != null) {
                    for (int i = 0; i < planResult.getStepList().size(); i++) {
                        int num = planResult.getStepList().get(i);
                        GoldAutumnJumpStep nextStep = new GoldAutumnJumpStep(num);
                        //最后一个珠子不在buff中
                        if(i != planResult.getStepList().size() - 1) {
                            //不是最后一个的，不可以再触发；标识已经有buff
                            nextStep.setSrcBuffId(4);
                        }
                        nextStep.getShowDta().setUseStep(num);
                        jumpCell(context, nextStep, userData, config, testMode);
                    }
                }

            } else if (buffInfo.getId() == 1) {
                //GoldAutumnMgr.getLogger().info("当前跳格子：{}, buff 好运十年", step.getCellId());
                //好运十年
                step.setBuff(new GoldAutumnBuff(1));

                step.getShowDta().setBuff(GoldAutumnProto.GoldAutumnBuffTemp.newBuilder().setId(1).setTimes(1));

                //日志
                if (!testMode){
                    AutoLogMgr.add(new LogGoldAutumnMove(userData.getUserId(), userData.getActivityId(), context.isAuto() ? 1 : 0,
                            step.getCost(), userData.getCurCellId(), step.getStep(), cell.getCt(), latticeInfo.getType(), latticeInfo.getId(), buffInfo.getId(), logScoreItem, ""));
                }

                for (int i = 0; i < 10; i++) {
                    GoldAutumnJumpStep nextStep = new GoldAutumnJumpStep(1);
                    jumpCell(context, nextStep, userData, config, testMode);
                }
            }

        } else {
            //道具奖励
            if (!StringUtils.isNullOrEmpty(cell.getR())) {
                Property property = PropertyHelper.parseStringToProperty(cell.getR());
                //奖励倍数
                if(property.getCountByGoodsId(config.getSCORE_ITEM_ID()).compareTo(BigInteger.ZERO) > 0){
                    logScoreItem += property.getCountByGoodsId(config.getSCORE_ITEM_ID()).intValue();
                }
                step.setProperty(property);
                step.getShowDta().setReward(PropertyHelper.parsePropertyToString(property));
                //GoldAutumnMgr.getLogger().info("当前跳格子：{}，普通奖励 {}", step.getCellId(), cell.getR());

                //日志
                if (!testMode){
                    AutoLogMgr.add(new LogGoldAutumnMove(userData.getUserId(), userData.getActivityId(), context.isAuto() ? 1 : 0,
                            step.getCost(), userData.getCurCellId(), step.getStep(), cell.getCt(), latticeInfo.getType(), latticeInfo.getId(), 0, logScoreItem, PropertyHelper.parsePropertyToString(property)));
                }
            }
        }
    }

}
